﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WinFromTools
{
    public partial class AdministrativeDivisionForm : Form
    {
        public AdministrativeDivisionForm()
        {
            InitializeComponent();
        }

        private void btnSelectOriginal_Click(object sender, EventArgs e)
        {
            //if (folderDialog.ShowDialog() == DialogResult.OK)
            //{
            //    txtOriginalPath.Text = folderDialog.SelectedPath;
            //}
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                txtOriginalPath.Text = fileDialog.FileName;
            }
        }

        private void btnParseXsdFiles_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtOriginalPath.Text) || txtOriginalPath.Text.Length < 4)
            {
                MessageBox.Show("请先选择Text文件");
            }
            else
            {
                //ParseXSDFiles(txtOriginalPath.Text, txtFileNames, txtOriginalPath.Text);
                //System.IO.File.WriteAllText(filename.ToLower().Replace(".xsd", ".html"), html);
                var sql = ParseTextFile(txtOriginalPath.Text);

                WriteLine(txtFileNames, sql);

                MessageBox.Show("处理完毕!");
            }
        }

        private static string ParseTextFile(string filename)
        {
            var lines = System.IO.File.ReadAllLines(filename);
            //var sb = new StringBuilder("");

            var divisions = new List<Division>();

            //string previous = null;
            foreach (var line in lines)
            {
                if (String.IsNullOrWhiteSpace(line))
                {
                    continue;
                }
                var l = line.Trim().Split(' ', '\t');
                if (l.Length > 1)
                {
                    var code = l[0];
                    if (code.EndsWith("0000"))
                    {
                        divisions.Add(new Division { code = code, name = l[1], abbreviation = l[1], displayOrder = 1, parentCode = "" });
                        continue;
                    }

                    if (code.EndsWith("00"))
                    {
                        var parent = divisions.FirstOrDefault(d => d.code == code.Substring(0, 2) + "0000");
                        if (parent == null)
                            continue;
                        parent.children.Add(new Division { code = code, name = l[1], abbreviation = l[1], displayOrder = Int32.Parse(code.Substring(2, 2)), parentCode = parent .code });
                    }

                    var province = divisions.FirstOrDefault(d => d.code == code.Substring(0, 2) + "0000");
                    var city = province.children.FirstOrDefault(c => c.code == code.Substring(0, 4) + "00");
                    if (city == null)
                    {
                        province.children.Add(new Division { code = code, name = l[1], abbreviation = l[1], displayOrder = Int32.Parse(code.Substring(4, 2)), parentCode = province.code });
                    }
                    else
                    {
                        city.children.Add(new Division { code = code, name = l[1], abbreviation = l[1], displayOrder = Int32.Parse(code.Substring(4, 2)), parentCode = city.code });
                    }   
                }
            }

            
            //System.IO.File.WriteAllText(filename.ToLower().Replace(".xsd", ".html"), html);

            return JsonConvert.SerializeObject(divisions);
        }

        private static void WriteLine(TextBox txtBox, String text)
        {
            txtBox.Focus();
            txtBox.AppendText(text + Environment.NewLine);
            txtBox.ScrollToCaret();
            System.Windows.Forms.Application.DoEvents();
        }
    }

    public class Division
    {
        public string code { get; set; }
        public string name { get; set; }
        public string abbreviation { get; set; }
        public int displayOrder { get; set; }
        public string parentCode { get; set; }
        public bool ignore { get; set; }

        private IList<Division> _children;
        public IList<Division> children
        {
            get { return _children ?? (_children = new List<Division>()); }
            protected set { _children = value; }
        }
    }
}
